<template>
  <div>
    <!-- 
        status-icon	是否在输入框中显示校验结果反馈图标
        rules	表单验证规则
        model	表单数据对象
     -->
    <el-form
      :model="loginForm"
      :rules="rules"
      ref="loginRef"
      label-width="120px"
      class="from"
      @keydown.enter="login(loginRef)"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login(loginRef)">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
//我们可以直接在script中 按照 js的语法去实现逻辑。但是要注意 要先引入后使用vue的方法
//vue3.0注意： import 一定要放到第一位
//setup 语法糖中没有this!!!!
import { userlogin } from "@/request/api";
import { reactive, ref } from "vue";
// 引入路由控制方法
import { useRouter } from "vue-router";
import { useStore } from "vuex";
let store = useStore();
// 引入自定义变量类型
import type { FormRules, FormInstance } from "element-plus";
// 设定路由控制方法
let route = useRouter();
// console.log(route,'路由');

let loginForm = reactive({
  username: "",
  password: "",
});

let rules = reactive<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 8, message: "长度应该为2-8个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 3, max: 10, message: "长度应该为3-10个字符", trigger: "blur" },
  ],
});
let loginRef = ref<FormInstance>();
const login = async (formEl: FormInstance | undefined) => {
  //   console.log(formEl);
  if (!formEl) return;
  await formEl.validate(async (val) => {
    if (val) {
      // console.log(val, "vvvvvvv");
      // console.log(store.dispatch('changeUserInfo',));
      let res = await userlogin(loginForm);
      if (res.code == 200) {
        console.log(res);
        store.dispatch("changeUserInfo", res.list);
      } else {
      }
      route.push("/index");
    } else {
      console.log(val, "失败了");
    }
  });
  //   console.log(loginForm, "登录对象");
};

// const keyDown = (e:any) => {
//   // console.log(e);
//   if(e.keyCode == 13 || e.keyCode == 100){
//     login(loginRef.value)
//   }
// }
</script>

<style lang="less" scoped>
.from {
  width: 500px;
  height: 300px;
  // background: #ccc;
  position: absolute;
  left: 450px;
  top: 250px;
}
</style>
